package com.qjs.activity.rookie.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.qjs.commom.ResponseUtils;

/**
 * <!-- 简单异常 -->
 * <bean class="com.qjs.activity.rookie.exception.GlobalExceptionResolver"> <!--
 * 设置日志输出级别，不定义则默认不输出警告等错误日志信息 -->
 * <property name="warnLogCategory" value="WARN"></property> <!--
 * 默认错误页面，当找不到上面mappings中指定的异常对应视图时，使用本默认配置 -->
 * <property name="defaultErrorView" value="500"></property> <!-- 默认HTTP状态码 -->
 * <property name="defaultStatusCode" value="500"></property>
 * 
 * <property name="exceptionAttribute" value="ex"/> <!-- 定义需要特殊处理的异常，这是重要点 -->
 * <property name="exceptionMappings"> <props>
 * <prop key="java.lang.Exception">500</prop> </props> </property> </bean>
 * 
 * @author Administrator
 *
 */
public class GlobalExceptionResolver extends SimpleMappingExceptionResolver {
	public static final Logger log = LoggerFactory.getLogger(GlobalExceptionResolver.class);

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		log.debug("resolveException开始" + ex.getMessage());
		String viewName = determineViewName(ex, request);
		response.setCharacterEncoding("UTF-8");
		if (viewName != null) {
			// JSP格式返回
			if (!(request.getHeader("accept").contains("application/json")
					|| (request.getHeader("X-Requested-With") != null
							&& request.getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
				// 如果不是异步请求
				log.debug("view开始");
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				System.out.println("JSP格式返回" + viewName);
				return getModelAndView(viewName, ex, request);
			} else {
				// JSON格式返回
				log.debug("json开始");
				try {
					String json = "{\"message\"：2}";
					ResponseUtils.renderJson(response, json);
				} catch (Exception e) {
					e.printStackTrace();
				}
				System.out.println("JSON格式返回" + viewName);
				return null;
			}
		} else {
			return null;
		}
	}
}
